using MediatR;
using Medical.Api.Write.Application.Command.DepartmentManagement.Recycling;
using Medical.Domain.DepartmentInfo;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Medical.Api.Write.Application.Handler.DepartmentManagement.Recycling
{
    public class DeleteRecyclingCommandHandler : IRequestHandler<DeleteRecyclingCommands, ApiResult<int>>
    {
        private readonly IBaseRepository<RecyclingTable> recyclingRep;
        private readonly IBaseRepository<ItemTable> itemRep;
        private readonly ILogger<DeleteRecyclingCommandHandler> logger;

        public DeleteRecyclingCommandHandler(
            IBaseRepository<RecyclingTable> recyclingRep,
            IBaseRepository<ItemTable> itemRep,
            ILogger<DeleteRecyclingCommandHandler> logger)
        {
            this.recyclingRep = recyclingRep;
            this.itemRep = itemRep;
            this.logger = logger;
        }

        public async Task<ApiResult<int>> Handle(DeleteRecyclingCommands request, CancellationToken cancellationToken)
        {
            try
            {
                logger.LogInformation("开始处理回收申请删除，ID：{0}", request.RecyclingId);

                // 检查回收申请是否存在
                var existingRecycling = await recyclingRep.GetModelAsync(request.RecyclingId);
                if (existingRecycling == null)
                {
                    logger.LogWarning("未找到ID为{0}的回收申请", request.RecyclingId);
                    return new ApiResult<int>
                    {
                        Code = ApiEnums.NotFound,
                        Data = 0,
                        Msg = $"未找到ID为{request.RecyclingId}的回收申请"
                    };
                }

                // 查找与该回收申请关联的所有物品
                var relatedItems = itemRep.GetAll().Where(i => i.RecyclingId == request.RecyclingId).ToList();

                // 软删除关联的物品
                foreach (var item in relatedItems)
                {
                    item.IsDeleted = true;
                    item.UpdateTime = DateTime.Now;
                    itemRep.Update(item);
                }

                // 软删除回收申请
                existingRecycling.IsDeleted = true;
                existingRecycling.UpdateTime = DateTime.Now;
                recyclingRep.Update(existingRecycling);

                logger.LogInformation("成功删除回收申请及相关物品，ID：{0}，物品数量：{1}", 
                    request.RecyclingId, relatedItems.Count());
                
                return new ApiResult<int>
                {
                    Code = ApiEnums.Success,
                    Data = request.RecyclingId,
                    Msg = "成功删除回收申请及相关物品"
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "删除回收申请时发生错误：{0}", ex.Message);
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Data = 0,
                    Msg = $"删除回收申请失败：{ex.Message}"
                };
            }
        }
    }
} 